import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { DeviceInspectionTemplateItemService } from './device-inspection-template-item.service';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-device-inspection-template-item-edit',
  templateUrl: './device-inspection-template-item-edit.component.html',
  styles: []
})
export class DeviceInspectionTemplateItemEditComponent implements OnInit {


  constructor(private msgSrv: NzMessageService,
              private deviceInspectionTemplateItemService: DeviceInspectionTemplateItemService,
  ) {
  }

  nzLoading = false;

  @Output() voted = new EventEmitter();

  isView: boolean = false;

  visible = false;
  deviceInspectionTemplateId: string;
  //检验项table数据
  listOfData: any[] = [];

  open(): void {
    this.visible = true;
  }

  edit(param) {
    this.visible = true;
    this.deviceInspectionTemplateId = param.id;

    this.deviceInspectionTemplateItemService.getByDeviceInspectionTemplateId(this.deviceInspectionTemplateId).subscribe(res => {
      if (res.code === 1) {
        this.listOfData = res.data;
      } else {
        this.msgSrv.error(res.message);
      }
    });

  }

  close(): void {
    this.visible = false;
  }

  getCaptcha(e: MouseEvent): void {
    e.preventDefault();
  }


  ngOnInit(): void {

  }

  onChange($event: string): void {
    console.log($event);
  }

  addOneRows() {
    this.listOfData.push({deviceInspectionTemplateId: this.deviceInspectionTemplateId});
    this.listOfData = [...this.listOfData];
  }

  delTable() {
    if (this.listOfData.some(item => {
      return item.checked;
    })) {
      for (let i = this.listOfData.length - 1; i >= 0; i--) {
        if (this.listOfData[i]['checked']) {
          let key = this.listOfData[i]['id'];
          this.listOfData.splice(i, 1);
          let temp = JSON.parse(localStorage.getItem('inspectionToTemplate'));
          if (temp && temp['id'] === key) {
            localStorage.removeItem('inspectionToTemplate');
          }
        }
      }
      this.listOfData = [...this.listOfData];
    }

  }

  checkAllInspectionList(bol) {
    if (bol) {
      this.listOfData.forEach(item => {
        item.checked = true;
      });
      this.listOfData = [...this.listOfData];
    } else {
      this.listOfData.forEach(item => {
        item.checked = false;
      });
      this.listOfData = [...this.listOfData];
    }

  }

  save() {

    this.nzLoading = true;

    this.deviceInspectionTemplateItemService.saveList(this.listOfData).subscribe(res => {

      this.nzLoading = false;

      if (res.code === 1) {
        this.msgSrv.success('保存完成');
        this.close();
        this.voted.emit();
      } else {
        this.msgSrv.error(res.message);
      }

    });

  }
}
